const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const config = require('config');
const logger = require('./logger');
const paramUtil = require('./paramUtil');
// const services = require('server-sdk').yonduService;
const url = require('url');

function get_uuid() {
  let s = [];
  const hexDigits = 'closeli666123456';
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = '4';
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  s[8] = s[13] = s[18] = s[23] = '-';

  const uuid = s.join('');
  return uuid;
}

passport.use(
  new LocalStrategy(
    {
      usernameField: 'username',
      passwordField: 'password',
      passReqToCallback: true,
    },
    function (req, username, password, done) {
      let param = paramUtil.getParams(req);
      const { projectCode } = param;
      let params = {
        user_name: username,
        user_pwd: password,
        project_code: projectCode,
        productKey: config.get('productKey'),
        FLOWINFO: get_uuid(),
      };
      // services['login'](req, params).then(resp => done(null, resp, params));
    }
  )
);

passport.serializeUser(function (user, done) {
  done(null, JSON.stringify(user));
});

passport.deserializeUser(function (user, done) {
  done(null, JSON.parse(user));
});

module.exports = {
  init(app) {
    app.use(passport.initialize());
    app.use(passport.session());
  },
  authenticateMiddleWare(req, res, next) {
    let pathname = url.parse(req.url).pathname;

    if (
      pathname.lastIndexOf('.') > pathname.lastIndexOf('/') ||
      /__webpack_hmr/.test(pathname) ||
      req.url === '/version' ||
      req.url === '/login' ||
      req.url === '/api/login' ||
      req.url === '/api/captcha' ||
      req.isAuthenticated()
    ) {
      return next();
    }

    logger.error(`未登录`, req.url);
    res.redirect('/login');
  },
};
